package com.hzy.utils;

import com.ruoyi.common.utils.redis.RedisUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.time.Duration;

/**
 * Copyright (C), 2022-2023
 * FileName: RedisExUtils
 * Description: Redis工具类扩展
 * Author:   zengxin
 * Date:     2023/10/21 12:04
 */
@Data
public class RedisExUtils  {

    /**
     * redis实现分布式锁 --- 上锁
     *
     * @param key
     * @param jobInfo
     * @param lockSecond
     * @return
     * @throws Exception
     */
    public static void lock(String key, String jobInfo, Integer lockSecond) throws Exception {
        String existJobInfo = RedisUtils.getCacheObject(key);
        if (StringUtils.isNotEmpty(existJobInfo)) {
            throw new Exception(String.format("获取锁失败: redisKey: %s, existJobInfo: %s", key, existJobInfo));
        }
        RedisUtils.setCacheObject(key, jobInfo, Duration.ofSeconds(lockSecond));
    }

    /**
     * redis实现分布式锁 --- 解锁
     *
     * @param key
     * @param jobInfo
     * @throws Exception
     */
    public static void unLock(String key, String jobInfo) throws Exception {
        String existJobInfo = RedisUtils.getCacheObject(key);
        if (jobInfo.equals(existJobInfo)) {
            RedisUtils.deleteObject(key);
        } else {
            throw new Exception(String.format("释放锁异常: redisKey: %s, existJobInfo: %s, jobInfo: %s", key, existJobInfo, jobInfo));
        }
    }
}
